package com.atguigu.gmall.payment.receiver;

import com.atguigu.gmall.common.constant.MqConst;
import com.atguigu.gmall.payment.service.PaymentInfoService;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @author: atguigu
 * @create: 2023-01-30 09:29
 */
@Component
@Slf4j
public class PaymentReceiver {

    @Autowired
    private PaymentInfoService paymentInfoService;

    /**
     * 监听关闭本地交易记录消息，修改本地交易记录状态为CLose
     * @param orderId
     * @param message
     * @param channel
     */
    @RabbitListener(bindings = @QueueBinding(
            exchange = @Exchange(MqConst.EXCHANGE_DIRECT_PAYMENT_CLOSE),
            value = @Queue(MqConst.QUEUE_PAYMENT_CLOSE),
            key = {MqConst.ROUTING_PAYMENT_CLOSE}
    ))
    public void closePayment(Long orderId, Message message, Channel channel) {
        try {
            if (orderId != null) {
                log.info("【支付微服务】监听关闭本地交易记录消息：{}", orderId);
                paymentInfoService.closePayment(orderId);
            }
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (IOException e) {
            e.printStackTrace();
            log.error("【支付微服务】,关闭本地交易记录异常：{}", e);
        }
    }

}
